/**
 * 创建延时任务
 * @param delay
 * @param callback
 */
export const delayTask = (delay: number, callback: () => void) => {
  const timeout = setTimeout(() => {
    clearTimeout(timeout);
    callback();
  }, delay);
  return timeout;
};

/**
 * 创建手动循环任务
 * @param option
 * @param fn
 */
export const manualTask = (
  option: { delay: number; immediate?: boolean },
  fn: (done: () => void, stop: () => void) => void
) => {
  let timeout: number;
  const stop = () => {
    timeout && clearTimeout(timeout);
  };
  const done = () => {
    stop();
    timeout = setTimeout(taskFn, option.delay);
  };
  const taskFn = () => fn(done, stop);
  option.immediate ? taskFn() : done();
  return stop;
};

/**
 * 创建自动循环任务
 * @param option
 * @param fn
 */
export const autoTask = (
  option: { delay: number; immediate?: boolean },
  fn: () => void
) => {
  let timeout: number;
  const stop = () => {
    timeout && clearInterval(timeout);
  };

  setInterval(fn, option.delay);

  option.immediate && fn();
  return stop;
};

/**
 * 倒计时
 */
export const createCountDown = (
  count: number, // 59
  callback: (e: { count: number; isFinish: boolean }) => void
) => {
  return {
    timerId: 0,
    start() {
      callback({ count, isFinish: false });
      let countDown = count;
      this.stop();
      (this as any).timerId = setInterval(() => {
        countDown--;
        if (countDown === 0) {
          this.stop();
        }
        callback({ count: countDown, isFinish: countDown === 0 });
      }, 1000);
    },
    stop() {
      clearInterval((this as any).timerId);
    },
  } as CountDown;
};

export interface CountDown {
  start: () => void;
  stop: () => void;
}
